<?php

namespace App\Models;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable implements MustVerifyEmail
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'phone',
        'birthday',
        'bio',
        'password',
        'is_active',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
        ];
    }

    /**
     * 获取用户的登录标识符名称
     */
    public function getLoginIdentifierName(): string
    {
        return 'email';
    }

    /**
     * 检查用户是否有邮箱
     */
    public function hasEmail(): bool
    {
        return !is_null($this->email);
    }

    /**
     * 检查用户是否有手机号
     */
    public function hasPhone(): bool
    {
        return !is_null($this->phone);
    }

    /**
     * 获取用户的主要联系方式
     */
    public function getPrimaryContact(): string
    {
        return $this->hasEmail() ? $this->email : $this->phone;
    }

    /**
     * 用户的收货地址
     */
    public function addresses(): HasMany
    {
        return $this->hasMany(UserAddress::class);
    }

    /**
     * 获取默认地址
     */
    public function defaultAddress()
    {
        return $this->addresses()->where('is_default', true)->first();
    }

    /**
     * 用户的订单
     */
    public function orders(): HasMany
    {
        return $this->hasMany(Order::class);
    }
}
